package com.example.RemindMe;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

public class AlarmTab extends Activity {
	private ArrayAdapter arrayAdapter;
	private ListView lv;
	public ArrayList<AlarmItem> datensaetze = new ArrayList<AlarmItem>();
	ArrayList<String> alarms = new ArrayList<String>();
	int position;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setRequestedOrientation(1);
		setContentView(R.layout.create_alarm);

		initDatensaetze();

		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface paraDialog, int paramButton) {
				switch (paramButton) {
				case DialogInterface.BUTTON_POSITIVE:
					// Hier kommt der Code hin, der beim linken Buttonklick
					// ausgef�hrt werden soll
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					// Hier kommt der Code hin, der beim rechten Buttonklick
					// ausgef�hrt werden soll
					break;

				}
			}
		};

		lv = (ListView) findViewById(R.id.listView1);
		arrayAdapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, alarms);
		lv.setAdapter(arrayAdapter);

		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent();
				intent.setClassName(getPackageName(), getPackageName()
						+ ".EditAlarmActivity");
				intent.putExtra("selected", datensaetze.get(arg2).getId());

				startActivity(intent);

                //geändert
                finish();
			}

		});

		lv.setLongClickable(true);

		lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View v,
					int index, long arg3) {

				position = index;
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(
						AlarmTab.this);

				alertDialog.setTitle("delete arlarm");

				alertDialog.setMessage("Are you sure, that you want to delete the selected alarm?");

				// Setting Positive "Yes" Button
				alertDialog.setPositiveButton("YES",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

								SharedPreferences settings = getSharedPreferences(
										"alarms", 0);
								Editor edit = settings.edit();
								edit.remove(datensaetze.get(position).getId());
								edit.commit();

								arrayAdapter.remove(arrayAdapter.getItem(position));
								arrayAdapter.notifyDataSetChanged();
								
								
								
								 Intent intent1 = new Intent(getApplicationContext(), AlarmReceiver.class);
								 PendingIntent sender1 = PendingIntent.getBroadcast(getApplicationContext(), Integer.parseInt(datensaetze.get(position).getId()), intent1, 0);
						         AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
						         am1.cancel(sender1);
						        
						         datensaetze.remove(position);
							}
						});

				// Setting Negative "NO" Button
				alertDialog.setNegativeButton("NO",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

								dialog.cancel();
							}
						});

				alertDialog.show();

				return true;

			}
		});

	}

	/**
	 * 
	 * Methode zum Aufrufen von CreateAlarm
	 * 
	 */
	public void createAlarm(View view) {
		Intent nextScreen = new Intent(this, CreateAlarm.class);
		startActivity(nextScreen);

        //geändert
        finish();
	}

	/**
	 * 
	 * Methode zum Initialisieren der Datens�tze um diese in einer ListView
	 * anzuzeigen. Die Datens�tze werden aus den SharedPreferences geholt, pro
	 * Datenatz wird ein AlarmItem erstellt und sodann sortiert.
	 * 
	 */
	public void initDatensaetze() {

		datensaetze.clear();
		SharedPreferences settings = getSharedPreferences("alarms", 0);
		Map<String, ?> items = settings.getAll();
		int i = 0;
		for (String s : items.keySet()) {

			String[] arrayData = items.get(s).toString().split(";");

			AlarmItem datensatz = new AlarmItem();
			datensatz.setId(s);

			datensatz.setText(arrayData[1]);
			datensatz.setTime(arrayData[0]);

			datensaetze.add(datensatz);
			Collections.sort(datensaetze, new SortByDate());

			// alarms.add(datensaetze.get(i).getText()+"\n"+datensaetze.get(i).getTime());

			// System.out.println(s);
		}

		/**
		 * 
		 * Datens�tze f�r die Ausgabe in der ListView aufbereiten (Anzeige)
		 * 
		 */
		for (AlarmItem s : datensaetze) {
			alarms.add(datensaetze.get(i).getText() + "\n"
					+ datensaetze.get(i).getTime());
			i++;
		}

	}

    //------------------------------------------------Action Bar Methods -----------------------------------------------
    public void onClickHome (View v)
    {
        goHome (this);
    }

    /**
     * Handle the click on the search button.
     *
     * @param v View
     * @return void
     */

    public void onClickSearch (View v)
    {
        startActivity (new Intent(getApplicationContext(), SearchActivity.class));

        //geändert
        finish();
    }

    /**
     * Handle the click on the About button.
     *
     * @param v View
     * @return void
     */

    public void onClickAbout (View v)
    {
        startActivity (new Intent(getApplicationContext(), AboutActivity.class));

        //geändert
        finish();
    }

    public void goHome(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);

        //geändert
        finish();
    }

    /**
     * Use the activity label to set the text in the activity's title text view.
     * The argument gives the name of the view.
     *
     * <p> This method is needed because we have a custom title bar rather than the default Android title bar.
     * See the theme definitons in styles.xml.
     *
     * @param textViewId int
     * @return void
     */

    public void setTitleFromActivityLabel (int textViewId)
    {
        TextView tv = (TextView) findViewById (textViewId);
        if (tv != null) tv.setText (getTitle ());
    } // end setTitleText

    /**
     * Show a string on the screen via Toast.
     *
     * @param msg String
     * @return void
     */

    public void toast (String msg)
    {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
    } // end toast

    /**
     * Send a message to the debug log and display it using Toast.
     */
    public void trace (String msg)
    {
        Log.d("Demo", msg);
        toast (msg);
    }

}